﻿using BW.WMS.WareHouseAllot.Doccode;
using BW.WMS.WareHouseAllot.Dto.Allot;
using BW.WMS.WareHouseAllot.Dto.Goods;
using BW.WMS.WareHouseAllot.Interface.Allot;
using BW.WMS.WareHouseAllot.Interface.Doccode;
using BW.WMS.WareHouseAllot.Parameter.Input.Allot;
using BW.WMS.WareHouseAllot.Parameter.Input.Goods;
using BW.WMS.WareHouseAllot.Parameter.Output.Allot;
using BW.WMS.WareHouseAllot.Parameter.Output.Goods;
using BW.WMS.WareHouseCheck;
using BW.WMS.WareHouseManage;
using BW.WMS.WareHouseStatistics.Page;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace BW.WMS.WareHouseAllot.Allot
{
    /// <summary>
    /// 仓库调拨实现接口
    /// </summary>
    public class AllotService : ApplicationService, IAllotService
    {
        private readonly IRepository<AllotModel> _allotRepository;
        private readonly IDoccodeService _doccodeService;
        private readonly IRepository<Department> _departRepository;
        private readonly IRepository<GoodsModel> _goodsRepository;
        private readonly IRepository<Warehouse> _wareHouseRepository;

        public AllotService(IRepository<AllotModel> AllotRepository,IDoccodeService doccodeService,IRepository<Department> DepartRepository,IRepository<GoodsModel> GoodsRepository,IRepository<Warehouse> WareHouseRepository)
        {
            _allotRepository = AllotRepository;
            this._doccodeService = doccodeService;
            _departRepository = DepartRepository;
            _goodsRepository = GoodsRepository;
            _wareHouseRepository = WareHouseRepository;
        }

        /// <summary>
        /// 添加仓库调拨信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<AllotDto> AddAllot(AddAllotInput input)
        {

            var allot = ObjectMapper.Map<AddAllotInput, AllotModel>(input);

            //调用自动生成编码服务
            allot.AllotCode = await _doccodeService.GenerateCodeAsync("仓库调拨");
            allot.CreateName = "admin";

            await _allotRepository.InsertAsync(allot);

            return ObjectMapper.Map<AllotModel, AllotDto>(allot);
        }

        

        /// <summary>
        /// 获取调拨信息数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<AllotOutput>> GetAllotList(AllotQuertInput input)
        {
            // 优化写法：使用IQueryable，在数据库层面过滤 (调拨)
            var allotQuery = await _allotRepository.GetQueryableAsync();
            var allot = allotQuery.Where(x => !x.IsDeleted);

            // 优化写法：使用IQueryable，在数据库层面过滤 (部门)
            var departMentQuery = await _departRepository.GetQueryableAsync();

            // 优化写法：使用IQueryable，在数据库层面过滤（货品信息）
            var goodsQuery = await _goodsRepository.GetQueryableAsync();
            var goods = goodsQuery.Where(x => !x.IsDeleted);

            // 优化写法：使用IQueryable，在数据库层面过滤（仓库信息）
            var wareHouseQuery = await _wareHouseRepository.GetQueryableAsync();

            //过滤条件
            if (!string.IsNullOrEmpty(input.AllotCode))
            {
                allot = allot.Where(x => x.AllotCode.Equals(input.AllotCode));
            }
            if (!string.IsNullOrEmpty(input.AllotStatus))
            {
                allot = allot.Where(x => x.AllotStatus.Equals(input.AllotStatus));
            }
            if (input.AllotTime != null)
            {
                allot = allot.Where(x => x.AllotTime.Value.AddDays(-1) < input.AllotTime && x.AllotTime.Value.AddDays(1) > input.AllotTime);
            }

            var linq = (from a in allot
                       join b in departMentQuery on a.DeptId equals b.Id
                       join c in goods on a.GoodsId equals c.Id
                       join d in wareHouseQuery on a.FoldWareHouseId equals d.Id
                       select new AllotOutput
                       {
                           Id = a.Id,
                           AllotCode = a.AllotCode,
                           AllotStatus = a.AllotStatus,
                           AllotType = a.AllotType,
                           AllotTime = a.AllotTime,
                           CalloutWareHouseId = d.Id,
                           CalloutWareHouseName = d.Name,
                           FoldWareHouseId = d.Id,
                           FoldWareHouseName = d.Name,
                           ApperStatus = a.ApperStatus,
                           GetStatus = a.GetStatus,
                           AllotNum = a.AllotNum,
                           AllotPrice = a.AllotPrice,
                           Operator = a.Operator,
                           GoodsId = c.Id,
                           GoodsName = c.GoodsName,
                           DeptId = b.Id,
                           DeptName = b.Depname,
                           PreparedBy = a.PreparedBy,
                           PreparedByTime = a.PreparedByTime,
                           AuditName = a.AuditName,
                           AuditTime = a.AuditTime,
                           AllotNotes = a.AllotNotes,
                           CreateName = a.CreateName,
                           UpdateName = a.UpdateName,
                           LastModificationTime = Convert.ToDateTime(a.LastModificationTime),
                           CreationTime = a.CreationTime,
                       }).ToList();

            // 4. 排序和分页
            var orderedQuery = linq.OrderBy(x => x.Id);
            var totalCount = orderedQuery.Count();
            var items = orderedQuery
                .Skip(input.SkipCount)
                .Take(input.MaxResultCount).ToList();

            // 5. 返回结果
            return new PagedResultDto<AllotOutput>()
            {
                 Items = items,
                  TotalCount = totalCount
            };
        }
    }
}
